﻿using MDK.Common;
using MDK.Model.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MDK.Winform
{
    public partial class frmInputFinger : BaseForm
    {
        private UInt32 N_ADDR = 0XFFFFFFFF;//设备地址
        private Bitmap bmp = new Bitmap(256, 288);//指纹图片
        private IntPtr DeviceHandle = IntPtr.Zero;
        private Thread CollectionThread = null;

        private bool IsCollection = false;
        public frmInputFinger()
        {
            InitializeComponent();
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            try
            {
                int result = DriveOperation.ZAZOpenDeviceEx(ref DeviceHandle, 2, 0, 0, 2, 0);
                if(result==0)
                {
                    SendMessage("打开指纹采集模块成功");
                    CollectionThread = new Thread(new ThreadStart(FigerCollection));
                    CollectionThread.Start();
                }
          
            }
            catch (Exception ex)
            {
                FastMessageBox.Show(ex.Message);
                SendMessage(string.Format("打开设备失败:{0}", ex.Message));
                StopCollection();
            }
            finally
            {

            }
        }

        #region 数据库访问

        private int GetMaxFingerId()
        {
            string url = string.Format("User/FindList?jsonWhere={0}&orderPropertyName={1}&isAsc=false", "", "");
            var list = WebAPIHelper.Get<List<T_User>>(url);
            if (list.Select(t => t.FingerID).Max() == null)
            {
                return 0;
            }
            return list.Select(t => t.FingerID).Max().Value + 1;
        }

        private void SaveFinger(int FingerId)
        {
            PropertyHelper jsonWhere = new PropertyHelper();
            jsonWhere.Addproperty(CompareType.Equal, "Id", App.currentUser.LoginID);
            string url = string.Format("User/Find?jsonWhere={0}", JsonConvert.SerializeObject(jsonWhere.propertyList));
            var user = WebAPIHelper.Get<T_User>(url);
            user.FingerID = FingerId;
            WebAPIHelper.Post<T_User>("User/Modify", user);
        }

        #endregion

        #region 采集指纹 结束采集
        /// <summary>
        /// 采集指纹
        /// </summary>
        private void FigerCollection()
        {
            int FingerID = GetMaxFingerId();
            while (!IsCollection)
            {
                try
                {
                    int ret = 0;
                    //	unsigned char ImgData [IMAGE_SIZE];
                    if (UpImage(DeviceHandle, N_ADDR, 1) != 1)
                    {
                        continue;
                    }
                    Thread.Sleep(200);
                    //7.获取指纹图像  8.上传指纹图像(可省略) 9.显示指纹图像(可省略) 10.生成特征B
                    if (UpImage(DeviceHandle, N_ADDR, 2) != 1)
                    {
                        continue;
                    }

                    Thread.Sleep(200);
                    /****************合成模板*********/
                    ret = DriveOperation.ZAZRegModule(DeviceHandle, N_ADDR);  //合并特征
                    if (ret != 0)
                    {
                        ShowErrorMess(ret);
                        continue;
                    }
                    else
                    {
                        SendMessage("合成指纹模板成功");
                    }
                    Thread.Sleep(200);

                    //本例以存在在指纹设备库中进行
                    ret = DriveOperation.ZAZStoreChar(DeviceHandle, N_ADDR, 1, FingerID);    //存放模板
                    if (ret != 0)
                    {
                        ShowErrorMess(ret);
                        continue;
                    }
                    else
                    {
                        SendMessage("存储指纹成功");
                        IsCollection = true;
                        StopCollection();
                    }
                }
                catch 
                {
                }
            }
        }

        private int UpImage(IntPtr hHandle, UInt32 nDevAddr, int buffer)
        {
            try
            {
                int ret = 0;
                byte[] ImgData = new byte[1024];
                int[] ImgLen = new int[1];
                int iBuffer = buffer;
                /****************获取图像*********/
                do
                {
                    SendMessage("请将手指平放在传感器上...");
                    ret = DriveOperation.ZAZGetImage(hHandle, nDevAddr);  //获取图象 
                }
                while (ret != DriveOperation.PS_OK);
                SendMessage("获取图像成功...");
                /****************生成特征 *********/
                ret = DriveOperation.ZAZGenChar(hHandle, nDevAddr, iBuffer);  //生成模板
                if (ret != 0)
                {
                    ShowErrorMess(ret);
                    return 0;
                }
                else
                {
                    SendMessage("生成指纹特征...");

                    MessageBox.Show("生成指纹特征...");
                    return 1;
                }
            }
            catch
            {
                return 0;
            }
            
        }

        private void StopCollection()
        {
            IsCollection = true;
            DriveOperation.ZAZCloseDeviceEx(DeviceHandle);
            SendMessage("停止采集...");
        }

        private void SendMessage(string str)
        {
            lbMessage.Invoke(new MethodInvoker(() =>
            {
                if (lbMessage.IsHandleCreated)
                {
                    lbMessage.Text =str;
                }
            }));
        }
        #endregion

        #region 显示指纹 显示错误
        /// <summary>
        /// 显示指纹图片
        /// </summary>
        /// <param name="rgbValues"></param>
        public void ShowFingerPrint(byte[] rgbValues)
        {
            bmp = new Bitmap(256, 238);
            for (int i = 0; i < bmp.Height; i++)
            {
                for (int j = 0; j < bmp.Width; j++)
                {
                    int value = (int)rgbValues[i * bmp.Width + j];
                    Color c = Color.FromArgb(value, value, value);

                    bmp.SetPixel(j, i, c);
                }
            }
            bmp.Save(string.Format(@"{0}\printer.bmp", Application.StartupPath));
        }

        /// <summary>
        /// 显示错误信息
        /// </summary>
        /// <param name="errorCode"></param>
        private void ShowErrorMess(int errorCode)
        {
            string sb = DriveOperation.ZAZErr2Str(errorCode);
            SendMessage(string.Format("录入指纹失败：{0}", sb));
        }

        private string PtrToStringUtf8(IntPtr ptr)
        {
            if (ptr == IntPtr.Zero)
                return "";
            int len = 0;
            while (System.Runtime.InteropServices.Marshal.ReadByte(ptr, len) != 0)
                len++;
            if (len == 0)
                return "";
            byte[] array = new byte[len];
            System.Runtime.InteropServices.Marshal.Copy(ptr, array, 0, len);
            return System.Text.Encoding.Default.GetString(array);
        }
        #endregion
    }
}
